package com.zzzzzz.oms.legs;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.validation.Validator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zzzzzz.core.datagrid.BaseData;
import com.zzzzzz.oms.orderHead.OrderHead;
import com.zzzzzz.oms.orderHead.OrderHeadDao;
import com.zzzzzz.oms.receipt.ReceiptDao;
import com.zzzzzz.oms.shipment.ShipmentDao;
import com.zzzzzz.oms.tempShipment.TempShipment;
import com.zzzzzz.oms.tempShipment.TempShipmentDao;
import com.zzzzzz.oms.tempShipment.TempShipmentService;
import com.zzzzzz.oms.wave.WaveService;
import com.zzzzzz.plugins.shiro.I;
import com.zzzzzz.utils.Arith;
import com.zzzzzz.utils.DateTimeUtils;

@Service
public class LegsService {
	@Resource
	public LegsDao legsDao;
	@Resource
	public OrderHeadDao orderHeadDao;
	@Resource
	public Validator validator;
	@Resource 
	public TempShipmentDao tempShipmentDao;
	@Resource 
	public TempShipmentService tempShipmentService;
	@Resource 
	public ShipmentDao shipmentDao;
	@Resource 
	public WaveService waveService;
	@Resource 
	public ReceiptDao receiptDao;
	String str[]={"-a","-b","-c","-d","-e","-f","-g","-h","-i","-j","-k","-l",
			"-m","-n","-o","-p","-q","-r","-s","-t","-u","-v","-w","-x","-y","-z"};
	//拆单
	@Transactional
	public int save(Legs legs,Legs leg, I i) {
		try {
			//表示已经存在啦
			legsDao.findBycomponentMark(leg.getId());	
			return -1;
		} catch (Exception e) {
			Double quantity=leg.getQuantity();
			Double weight=leg.getWeight();
			Double volume=leg.getVolume();
			Double palletsum=leg.getPalletsum();
			leg.setQuantity(legs.getQuantity());
			leg.setWeight(legs.getWeight());
			leg.setVolume(legs.getVolume());
			leg.setPalletsum(legs.getPalletsum());
			leg.setUpdBy(i.getId());
			leg.setUpdDt(new Date());
			legsDao.updById(leg);
			try {
				int num=Arrays.binarySearch(str, leg.getLegs_no().substring(leg.getLegs_no().length()-2, leg.getLegs_no().length()));
				leg.setLegs_no(leg.getLegs_no().substring(0,leg.getLegs_no().length()-2)+str[num+1]);
				leg.setUpdBy(null);
				leg.setUpdDt(null);
				leg.setAddBy(i.getId());
				leg.setAddDt(new Date());
				leg.setQuantity(Arith.sub(Arith.round(quantity, 8), Arith.round(legs.getQuantity(), 8)));
				leg.setWeight(Arith.sub(Arith.round(weight, 8), Arith.round(legs.getWeight(), 8)));
				leg.setVolume(Arith.sub(Arith.round(volume, 8), Arith.round(legs.getVolume(), 8)));
				leg.setVolume(Arith.sub(Arith.round(volume, 8), Arith.round(legs.getVolume(), 8)));
				leg.setPalletsum(Arith.sub(Arith.round(palletsum, 8), Arith.round(legs.getPalletsum(), 8)));
				leg.setComponentMark(leg.getId());
				leg.setComponent("竖拆");
				legsDao.add(leg);
				tempShipmentDao.updPointsById(leg.getTempshipmentId(),i);
			} catch (Exception e2) {
				leg.setLegs_no(leg.getLegs_no()+"-a");
				leg.setUpdBy(null);
				leg.setUpdDt(null);
				leg.setAddBy(i.getId());
				leg.setAddDt(new Date());
				leg.setQuantity(Arith.sub(Arith.round(quantity, 8), Arith.round(legs.getQuantity(), 8)));
				leg.setWeight(Arith.sub(Arith.round(weight, 8), Arith.round(legs.getWeight(), 8)));
				leg.setVolume(Arith.sub(Arith.round(volume, 8), Arith.round(legs.getVolume(), 8)));
				leg.setPalletsum(Arith.sub(Arith.round(palletsum, 8), Arith.round(legs.getPalletsum(), 8)));
				leg.setComponentMark(leg.getId());
				leg.setComponent("竖拆");
				legsDao.add(leg);
				tempShipmentDao.updPointsById(leg.getTempshipmentId(),i);
			}
		}
		return 1;
	}
	
	//删除分段订单
	public String delByIds1(List<Legs> list,I i){	
		sort(list);
		for(Legs legs:list){
			String cd=legs.getLegs_no().substring(0,legs.getLegs_no().length()-2);
			try {
				Legs legss=legsDao.findBycomponentMark(legs.getId());	
				return legss.getLegs_no();
			} catch (Exception e) {
				Legs leg=legsDao.findByCd(cd);
				leg.setUpdBy(i.getId());
				leg.setUpdDt(new Date());
				leg.setQuantity(Arith.add(legs.getQuantity(), leg.getQuantity()));
				leg.setWeight(Arith.add(legs.getWeight(), leg.getWeight()));
				leg.setVolume(Arith.add(legs.getVolume(), leg.getVolume()));
				leg.setPalletsum(Arith.add(legs.getPalletsum(), leg.getPalletsum()));
				legsDao.delByIds1(legs.getId());
				legsDao.updById(leg);
				tempShipmentDao.updPointsById1(leg.getTempshipmentId(),i);
			}
		}
		return null;
	}
	
	//主要用于调度的跟踪
	public int findByShipmentId(List<Long> shipmentIds ,String status,I i){
		List<Legs> list=legsDao.findListByShipmentIds(shipmentIds, i);
		if(status.equals("arrive")){
			updMustDtByOrderId(list);
		}
		if(list.size()>0){
			for(Legs legs:list){
				legsDao.zz("t_order_head", null, status, "orderId", legs.getOrderId());
			}
		}
		return 1;
	}
	
	@Transactional
	public List<BaseData> batchAdd(List<Legs> list, I i) {
		logger.info("legs batchAdd validate start:" + DateTimeUtils.date2Str(new Date(), DateTimeUtils.FORMAT_YYYY_MM_DD_HH_MM_SS));
		List<BaseData> listMsg=new ArrayList<BaseData>();
		int count=0;
		for (Legs legs : list) {
			if(legs.getWaveCd()!=null&&!legs.getWaveCd().equals("")){
				count++;
				legsDao.updWaveIdById(waveService.getWaveByCd(legs.getWaveCd(), i.getPlatformId()), legs.getId(), i);
			}
		}
		BaseData baseData = new BaseData();
		baseData.setErrMsg("总共有"+list.size()+"行记录；共有"+count+"行记录更新了波次；共有"+(list.size()-count)+"行记录没有更新波次；");
		listMsg.add(baseData);
		logger.info("legs batchAdd save end:" + DateTimeUtils.date2Str(new Date(), DateTimeUtils.FORMAT_YYYY_MM_DD_HH_MM_SS));
		return listMsg;
	}
	
	//生成legs	
	public Legs add(OrderHead orderHead,I i){
		Legs legs=new Legs();
		legs.setOrderId(orderHead.getId());
		legs.setOrderCd(orderHead.getCd());
		legs.setLegs_no(orderHead.getCd()+"_1");
		legs.setSt("shipment");
		legs.setStatus(orderHead.getStatus());
		legs.setPlatformId(i.getPlatformId());
		legs.setAddDt(new Date());
		legs.setAddBy(i.getId());
		legs.setVocationType(orderHead.getVocation());
		legs.setClientId(orderHead.getClientId());
		if(tempShipmentDao.findIdByCd("未配载", orderHead.getVocation(),i)==null){
			TempShipment tempShipment=new TempShipment();
			tempShipment.setVocationType(orderHead.getVocation());
			tempShipment.setPlatformId(i.getPlatformId());
			tempShipment.setExpectMoney(0.0);
			tempShipment.setExpense(0.0);
			tempShipment.setAddBy(i.getId());
			tempShipment.setAddDt(new Date());
			tempShipment.setCode("未配载");
			tempShipmentDao.add(tempShipment);
		}
		legs.setTempshipmentId(tempShipmentDao.findIdByCd("未配载", orderHead.getVocation(),i).getId());
		legs.setShipment_method(orderHead.getShipment_method());
		legs.setFormId(orderHead.getFreceiverId());
		legs.setToId(orderHead.getTreceiverId());
		legs.setFtranslocationId(orderHead.getFtranslocationId());
		legs.setTtranslocationId(orderHead.getTtranslocationId());
		legs.setFormName(orderHead.getFreceiverName());
		legs.setFormlikeName(orderHead.getFreceiverLikename());
		legs.setFormPhone(orderHead.getFreceiverPhone());
		legs.setFormAddr(orderHead.getFreceiverAddress());
		legs.setToName(orderHead.getTreceiverName());
		legs.setTolikeName(orderHead.getTreceiverLikename());
		legs.setToPhone(orderHead.getTreceiverPhone());
		legs.setToAddr(orderHead.getTreceiverAddress());
		legs.setQuantity(orderHead.getQuantity());
		legs.setWeight(orderHead.getWeight());
		legs.setVolume(orderHead.getVolume());
		legs.setPalletsum(orderHead.getPalletsum());
		legs.setExpense(orderHead.getExpense());
		legs.setOrdertime(orderHead.getOrderDt());
		legs.setBilltime(orderHead.getBillingDt());
		legs.setPlanltime(orderHead.getPlanlDt());
		legs.setPlanatime(orderHead.getPlanaDt());
		return legs;
	}
		
	// 调度订单里面取消分段订单
	public void updByIds(List<Long> ids,String vocationType,Long shipmentId,I i){
		TempShipment temp=tempShipmentDao.findIdByCd("未配载", vocationType, i);
		legsDao.updByIds(ids, temp.getId(), i);
		changeQx(temp.getId(),shipmentId, i);
	}
		
	// 调度单里面增加分段订单
	public void updByIds1(List<Long> ids,Long shipmentId,Long constractorId,String shipment_method,String vocationType,I i){
		TempShipment temp=tempShipmentDao.findIdByCd("未配载", vocationType, i);
		legsDao.updByIds1(ids, shipmentId, constractorId, shipment_method, i);
		changeAd(temp.getId(), shipmentId, i);
	}
		
	// 更新temp和shipment
	public void changeQx(Long tempShipmentId,Long shipmentId,I i){
		TempShipment tempShipment = tempShipmentService.build(tempShipmentId, i);
		tempShipment.setId(tempShipmentId);
		tempShipmentDao.updById(tempShipment);
		Legs leg=legsDao.findshipmentIds(shipmentId);
		if(leg.getQuantity()==null){
			leg.setQuantity(0.0);
		}
		if(leg.getWeight()==null){
			leg.setWeight(0.0);
		}
		if(leg.getVolume()==null){
			leg.setVolume(0.0);
		}
		if(leg.getPalletsum()==null){
			leg.setPalletsum(0.0);
		}
		shipmentDao.upds(shipmentId, leg.getQuantity(),leg.getWeight(),leg.getVolume(),leg.getPalletsum(),leg.getCount(), i);
	}
		
	// 调度单里面增加分段订单的时候,更新temp和shipment
	public void changeAd(Long tempShipmentId,Long shipmentId,I i){
		TempShipment tempShipment = tempShipmentService.build(tempShipmentId, i);
		tempShipment.setId(tempShipmentId);
		tempShipmentDao.updById(tempShipment);
		Legs leg=legsDao.findshipmentIds(shipmentId);
		shipmentDao.upds(shipmentId, leg.getQuantity(),leg.getWeight(),leg.getVolume(),leg.getPalletsum(),leg.getCount(), i);
	}
		
	// 更新应回单时间	
	public void updMustDtByOrderId(List<Legs> list){
		for(Legs legs : list){
			legsDao.updMustDtByOrderId(receiptDao.timeControl(legs.getClientId(), legs.getCityName()), legs.getOrderId());
		}
	}
		
	//对list 进行排序
	private static void sort(List<Legs> data) { 
	    Collections.sort(data, new Comparator<Legs>() {
	    public int compare(Legs o1, Legs o2) {
	        Long a =o1.getId();
	        Long b = o2.getId();
	         // 降序
	         return b.compareTo(a);
	       }
	    });
	}
	private static final Logger logger = LoggerFactory.getLogger(Legs.class);
}
